# !/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Project : pytest-allure-selenium-po-demo
# @Time    : 2023/2/16 14:27
# @Author  : mojin
# @Email   : 397135766@qq.com
# @File    : screen_recordings.py
# @Software: PyCharm
# -------------------------------------------------------------------------------
import cv2
import subprocess
import re
import threading
import numpy as np
from pynput.mouse import Controller
from PIL import ImageGrab, ImageDraw
from common.loggers import Logger


class PcScreen():  # 电脑端录屏
    def __init__(self, images_path='out.mp4', fps=16):
        self.images_path = images_path
        self.flag = False
        self._status = False
        self._fps = fps

    def record_screen(self):

        screen = ImageGrab.grab()
        width, high = screen.size

        fourcc = cv2.VideoWriter_fourcc(*'avc1')
        video = cv2.VideoWriter(self.images_path, fourcc, self._fps, (width, high), True)
        #image_lst = []
        n = 1
        m = Controller()

        while True:
            if self.flag:
                break

            img = ImageGrab.grab()
            co = m.position  # 获取当前鼠标位置
            x = co[0]
            y = co[1]
            draw = ImageDraw.Draw(img)  # 画一个鼠标
            draw.polygon([(x, y), (x + 30, y + 20), (x + 20, y + 30)], fill=(255, 0, 0))  # 画个三角形，红色填充

            imm = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)  # 转为opencv的BGR模式

            #image_lst.append(imm)
            video.write(imm)

            n = n + 1

        video.release()
        self._status = True

    def status(self):
        return self._status

    def stop(self):
        self.flag = True
        while True:
            if self.status():
                break

        return self.status()  #

    def start(self):
        th = threading.Thread(target=self.record_screen)
        th.start()


class MobileScreen():  # 手机录屏
    def __init__(self, images_path='out.mp4', devices='', fps=2, ratio=3):  #
        self.images_path = images_path  # 保存路径
        self._fps = fps  # 保存视频帧率  fps 默认为2 暂时不建议修改
        self.devices = devices  # adb  devices  设备序列号
        self.ratio = ratio  # 输出视频的缩小比例，默认3，缩小原来的1/3
        self.flag = False  # 判断是否结束录屏关键字
        self._status = False  # 判断是否结束完成录屏关键字
        self.width = None  # 缩小比例后的宽度
        self.high = None  # 缩小比例后的高度

    def get_resolving_power(self):  # 获取分辨率,按比例缩小
        img = str(self.execute_adb('shell wm size'))
        m = re.findall('\d+', img)
        if m != []:
            self.width = int(int(m[0]) / self.ratio)
            self.high = int(int(m[1]) / self.ratio)
        else:
            Logger.error(f'没有获取到分辨率！！{m}')

    def execute_adb(self, cmd):  # 执行adb 命令
        if self.devices == '':
            dev_shell = self.devices
        else:
            dev_shell = f'-s {self.devices}'
        try:
            result = subprocess.Popen(f'adb {dev_shell} ' + cmd, shell=True, stdout=subprocess.PIPE)
            out, err = result.communicate()

        except Exception as e:
            Logger.error(f'执行adb 命令 失败!!（{e}）')
            raise
        # return out.replace(b'\r\r\n', b'\n')  # Android6及以下
        return out.replace(b'\r\n', b'\n')  # Android7及以上

    def screen(self):  # 获取img
        try:
            img = self.execute_adb('shell screencap -p')

            screen_img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_COLOR)
            resizeImg = cv2.resize(screen_img, (self.width, self.high))  # 这里改为自己想要的分辨率
        except Exception as e:
            Logger.error(f'获取图像失败!!（{e}）')
            raise
        return resizeImg

    def record_screen(self):  # 持续录屏
        self.get_resolving_power()

        # screen_img=self.screen()
        # #high, width,xxh=screen_img.shape

        # width, high,h=img.shape
        # 1080, 2340
        # width, high=480,720

        fourcc = cv2.VideoWriter_fourcc(*'avc1')
        video = cv2.VideoWriter(self.images_path, fourcc, self._fps, (self.width, self.high), True)

        n = 1
        while True:
            if self.flag:
                break
            screen_img = self.screen()
            video.write(screen_img)
            n = n + 1
        video.release()
        self._status = True

    def status(self):
        return self._status

    def stop(self):
        self.flag = True
        while True:
            if self.status():
                break
        return self.status()  #

    def start(self):
        th = threading.Thread(target=self.record_screen)
        th.start()
